<template>
	<view class="order-detail-page">
		<!-- 1. 顶部状态和倒计时 -->
		<view class="header-status">
			<view class="status-line">
				<text class="status-text">{{ orderStatusText }}</text>
				<uni-icons v-if="order.status === 'pending_payment'" type="pulldown" size="18" color="#333" @click="toggleCountdownVisibility"></uni-icons>
			</view>
			<view class="countdown-timer" v-if="order.status === 'pending_payment' && showCountdown">
				<text class="time-segment">{{ countdown.hours }}</text>时
				<text class="time-segment">{{ countdown.minutes }}</text>分
				<text class="time-segment">{{ countdown.seconds }}</text>秒内未付款，订单将自动关闭
			</view>
		</view>

		<!-- 2. 地址信息 -->
		<view class="address-section card-style">
			<uni-icons type="location-filled" size="20" color="#666" class="location-icon"></uni-icons>
			<view class="address-details">
				<view class="contact-info">
					<text class="name">{{ order.address.name }}</text>
					<text class="phone">{{ order.address.phone }}</text>
				</view>
				<text class="full-address">{{ order.address.fullAddress }}</text>
			</view>
			<button v-if="order.status === 'pending_payment'" class="modify-address-btn" size="mini" @click="modifyAddress">修改地址</button>
		</view>

		<!-- 3. 商品信息 -->
		<view class="product-section card-style">
			<image class="product-image" :src="order.product.imageUrl" mode="aspectFill"></image>
			<view class="product-info">
				<text class="product-name">{{ order.product.name }}</text>
				<!-- 可以添加规格等信息 -->
			</view>
			<text class="product-price">¥{{ order.product.price.toFixed(2) }}</text>
		</view>

		<!-- 4. 价格明细 -->
		<view class="price-details-section card-style">
			<view class="price-item">
				<text class="label">成交价</text>
				<uni-icons :type="showMorePriceDetails ? 'arrowup' : 'arrowdown'" size="16" color="#999" @click="togglePriceDetails"></uni-icons>
				<text class="value actual-price">¥{{ order.totalAmount.toFixed(2) }}</text>
			</view>
			<view v-if="showMorePriceDetails">
				<view class="price-item">
					<text class="label">商品总价</text>
					<text class="value">¥{{ order.productAmount.toFixed(2) }}</text>
				</view>
				<view class="price-item">
					<text class="label">运费</text>
					<text class="value">¥{{ order.shippingFee.toFixed(2) }}</text>
				</view>
				<!-- 可以添加优惠、积分抵扣等 -->
			</view>
		</view>
		
		<!-- 5. 订单信息 -->
		<view class="order-info-section card-style">
			<view class="info-item">
				<text class="label">订单编号</text>
				<text class="value">{{ order.orderSn }}</text>
				<button class="copy-btn" size="mini" @click="copyText(order.orderSn)">复制</button>
			</view>
			<view class="info-item" @click="gotoTransactionDispute">
				<text class="label">交易快照</text>
				<text class="value placeholder">发生交易争议时，可作为判断依据</text>
				<uni-icons type="right" size="16" color="#C0C4CC"></uni-icons>
			</view>
			<view class="info-item" v-if="order.paymentSn">
				<text class="label">支付宝交易号</text>
				<text class="value">{{ order.paymentSn }}</text>
				<button class="copy-btn" size="mini" @click="copyText(order.paymentSn)">复制</button>
			</view>
			<view class="info-item" v-if="order.createTime">
				<text class="label">创建时间</text>
				<text class="value">{{ formatTime(order.createTime) }}</text>
			</view>
			<view v-if="showMoreOrderInfo">
				<view class="info-item" v-if="order.paymentTime">
					<text class="label">付款时间</text>
					<text class="value">{{ formatTime(order.paymentTime) }}</text>
				</view>
				<view class="info-item" v-if="order.shippingTime">
					<text class="label">发货时间</text>
					<text class="value">{{ formatTime(order.shippingTime) }}</text>
				</view>
				<view class="info-item" v-if="order.receiveTime">
					<text class="label">确认收货时间</text>
					<text class="value">{{ formatTime(order.receiveTime) }}</text>
				</view>
			</view>
			<view class="toggle-more-info" @click="toggleOrderInfoVisibility" v-if="hasMoreOrderInfoToShow">
				<text>{{ showMoreOrderInfo ? '收起' : '查看更多' }}</text>
				<uni-icons :type="showMoreOrderInfo ? 'arrowup' : 'arrowdown'" size="16" color="#999"></uni-icons>
			</view>
		</view>

		<!-- 6. 为你推荐 (占位) -->
		<view class="recommendation-section">
			<view class="rec-title">
				<uni-icons type="heart-filled" color="#FF5000" size="20" style="margin-right: 8rpx;"></uni-icons>
				为你推荐
			</view>
			<!-- 推荐商品列表 -->
			<view class="rec-placeholder">--- 推荐商品区域 ---</view>
		</view>

		<!-- 7. 底部操作栏 -->
		<view class="bottom-actions" :style="{ paddingBottom: safeAreaInsetsBottom + 'px' }">
			<button class="action-btn secondary-btn" @click="contactSeller">
				<uni-icons type="chatbubble" size="18" color="#555" style="margin-right: 6rpx;"></uni-icons>
				联系卖方
			</button>
			<button v-if="order.status === 'pending_payment'" class="action-btn" @click="openCancelOrderDrawer">取消订单</button>
			<button v-if="order.status === 'pending_payment'" class="action-btn primary-btn" @click="goToPayment">去付款</button>
			<button v-if="order.status === 'paid'" class="action-btn" @click="viewLogistics">查看物流</button>
			<button v-if="order.status === 'shipped'" class="action-btn primary-btn" @click="confirmReceipt">确认收货</button>
			<button v-if="order.status === 'completed' && !order.isReviewed" class="action-btn" @click="rateOrder">评价订单</button>
			<button v-if="order.status === 'completed' || order.status === 'closed'" class="action-btn" @click="buyAgain">再次租用</button>
		</view>
		<!-- 底部安全区占位，防止内容被操作栏遮挡 -->
		<view :style="{ height: bottomBarHeight + 'px' }"></view>


		<!-- 取消订单原因抽屉 -->
		<uni-popup ref="cancelOrderDrawer" type="bottom" background-color="#fff" @change="onDrawerChange">
			<view class="cancel-drawer-content">
				<text class="drawer-title">请选择取消订单原因</text>
				<radio-group @change="cancelReasonChange">
					<label v-for="(reason, index) in cancelReasons" :key="index" class="reason-item">
						<text>{{ reason.text }}</text>
						<radio :value="reason.value" :checked="reason.value === selectedCancelReason" color="#FFC800" style="transform:scale(0.8)" />
					</label>
				</radio-group>
				<view class="drawer-actions">
					<button class="drawer-btn secondary" @click="closeCancelOrderDrawer">暂不取消</button>
					<button class="drawer-btn primary" @click="confirmCancelOrder" :disabled="!selectedCancelReason">取消订单</button>
				</view>
				<view :style="{ height: safeAreaInsetsBottom + 'px' }"></view> <!-- 底部安全区 -->
			</view>
		</uni-popup>

	</view>
</template>

<script>
const app = getApp()
export default {
	data() {
		return {
			order: { // 模拟订单数据
				id: '12345',
				status: 'pending_payment', // 'pending_payment', 'paid', 'shipped', 'completed', 'closed', 'cancelled'
				orderSn: '4344816891511410545',
				paymentSn: '11170600025051820918659414505',
				createTime: Date.now() - 30 * 60 * 1000, // 30分钟前创建
				paymentExpireTime: Date.now() + (23 * 3600 + 59 * 60 + 52) * 1000, // 模拟一个未来的过期时间
				paymentTime: null,
				shippingTime: null,
				receiveTime: null,
				isReviewed: false,
				address: {
					name: '周尼木',
					phone: '18639433190',
					fullAddress: '北京北京市朝阳区 十八里店镇朝阳区小武基紫晶百姓大药房往西200米路南华联生活超市'
				},
				product: {
					id: 'p001',
					name: '金收质子不是r',
					imageUrl: '/static/avatar_axpg.png', // 替换为实际商品图
					price: 6.00,
				},
				productAmount: 6.00,
				shippingFee: 0.00,
				totalAmount: 6.00,
			},
			countdown: {
				hours: '00',
				minutes: '00',
				seconds: '00'
			},
			countdownInterval: null,
			showCountdown: true,
			showMorePriceDetails: false,
			showMoreOrderInfo: false,
			safeAreaInsetsBottom: 0,
			bottomBarHeight: 60, // 预估底部操作栏高度

			// 取消订单相关
			cancelReasons: [
				{ text: '我不想买了', value: '不想买了' },
				{ text: '信息填写错误，重新拍', value: '信息错误' },
				{ text: '卖家缺货', value: '卖家缺货' },
				{ text: '同城见面交易', value: '同城交易' },
				{ text: '其他原因', value: '其他' }
			],
			selectedCancelReason: '',
		};
	},
	computed: {
		orderStatusText() {
			switch (this.order.status) {
				case 'pending_payment': return '请您尽快付款';
				case 'paid': return '等待卖家发货';
				case 'shipped': return '卖家已发货';
				case 'completed': return '订单已完成';
				case 'closed': return '订单已关闭';
				case 'cancelled': return '订单已取消';
				default: return '未知状态';
			}
		},
		hasMoreOrderInfoToShow() {
			// 根据实际订单信息判断是否还有更多可显示
			return this.order.paymentTime || this.order.shippingTime || this.order.receiveTime;
		}
	},
	onLoad(options) {
		this.order.id = options.id;
		// const orderId = options.id;
		// this.loadOrderDetail(orderId); // 实际项目中根据ID加载订单

		if (this.order.status === 'pending_payment') {
			this.startCountdown();
		}

		const { safeAreaInsets } = uni.getSystemInfoSync();
		if (safeAreaInsets) {
			this.safeAreaInsetsBottom = safeAreaInsets.bottom;
		}
	},
	onShow(){
		if(this.order?.id){
			this.loadOrderDetail();
		}
	},
	onReady() {
		// 获取底部操作栏实际高度，用于占位
		const query = uni.createSelectorQuery().in(this);
		query.select('.bottom-actions').boundingClientRect(data => {
		  if (data && data.height) {
		    this.bottomBarHeight = data.height + 10; // 加一点padding
		  }
		}).exec();
	},
	onUnload() {
		if (this.countdownInterval) {
			clearInterval(this.countdownInterval);
		}
	},
	methods: {
		loadOrderDetail(){
			app.globalData.Request.post(app.globalData.ApiConstant.Order.info, {
				orderId: this.order.id
			}).then((res)=> {
				this.order = res.data
				console.log(res)
			})
		},
		formatTime(timestamp) {
			if (!timestamp) return '';
			return //dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss');
		},
		startCountdown() {
			if (this.countdownInterval) clearInterval(this.countdownInterval);
			
			const update = () => {
				const now = Date.now();
				const timeLeft = this.order.paymentExpireTime - now;

				if (timeLeft <= 0) {
					this.countdown = { hours: '00', minutes: '00', seconds: '00' };
					clearInterval(this.countdownInterval);
					this.handleOrderTimeout();
					return;
				}

				const hours = Math.floor(timeLeft / (1000 * 60 * 60));
				const minutes = Math.floor((timeLeft % (1000 * 60 * 60)) / (1000 * 60));
				const seconds = Math.floor((timeLeft % (1000 * 60)) / 1000);

				this.countdown.hours = String(hours).padStart(2, '0');
				this.countdown.minutes = String(minutes).padStart(2, '0');
				this.countdown.seconds = String(seconds).padStart(2, '0');
			};
			
			update(); // 立即执行一次
			this.countdownInterval = setInterval(update, 1000);
		},
		handleOrderTimeout() {
			console.log("订单已超时");
			uni.showToast({ title: '订单已超时自动关闭', icon: 'none', duration: 2000 });
			this.order.status = 'closed'; // 更新订单状态
			// 你可能需要调用API通知后端订单关闭
		},
		toggleCountdownVisibility() {
			if (this.order.status === 'pending_payment') {
				this.showCountdown = !this.showCountdown;
			}
		},
		togglePriceDetails() {
			this.showMorePriceDetails = !this.showMorePriceDetails;
		},
		toggleOrderInfoVisibility() {
			this.showMoreOrderInfo = !this.showMoreOrderInfo;
		},
		copyText(text) {
			uni.setClipboardData({
				data: text,
				success: () => {
					uni.showToast({ title: '复制成功', icon: 'none' });
				}
			});
		},
		modifyAddress() {
			uni.showToast({ title: '修改地址功能', icon: 'none' });
			// uni.navigateTo({ url: '/pages/user/AddressListPage?selectMode=true&orderId=' + this.order.id });
		},
		gotoTransactionDispute() {
			uni.showToast({ title: '查看交易快照', icon: 'none' });
		},
		contactSeller() {
			uni.showToast({ title: '联系卖家', icon: 'none' });
			// uni.navigateTo({ url: '/pages/chat/ChatPage?sellerId=' + this.order.sellerId });
		},
		openCancelOrderDrawer() {
			this.selectedCancelReason = ''; // 重置选择
			this.$refs.cancelOrderDrawer.open();
		},
		closeCancelOrderDrawer() {
			this.$refs.cancelOrderDrawer.close();
		},
		onDrawerChange(e) {
			// console.log('Cancel drawer state:', e.show);
		},
		cancelReasonChange(e) {
			this.selectedCancelReason = e.detail.value;
		},
		confirmCancelOrder() {
			if (!this.selectedCancelReason) {
				uni.showToast({ title: '请选择取消原因', icon: 'none' });
				return;
			}
			uni.showLoading({ title: '正在取消...' });
			// 模拟API调用
			setTimeout(() => {
				uni.hideLoading();
				this.order.status = 'cancelled'; // 更新订单状态
				this.closeCancelOrderDrawer();
				uni.showToast({ title: '订单已取消', icon: 'success' });
				if (this.countdownInterval) clearInterval(this.countdownInterval); // 停止倒计时
			}, 1000);
		},
		goToPayment() {
			uni.showLoading({ title: '正在处理...' });
			// 模拟支付过程
			setTimeout(() => {
				uni.hideLoading();
				uni.showToast({ title: '付款成功！', icon: 'success', duration: 1500 });
				this.order.status = 'paid'; // 更新订单状态
				this.order.paymentTime = Date.now();
				if (this.countdownInterval) clearInterval(this.countdownInterval); // 停止倒计时
				setTimeout(() => {
					uni.navigateBack();
				}, 1500);
			}, 2000);
		},
		// 其他按钮的占位方法
		viewLogistics() { uni.showToast({ title: '查看物流', icon: 'none' }); },
		confirmReceipt() { uni.showToast({ title: '确认收货', icon: 'none' }); this.order.status = 'completed'; this.order.receiveTime = Date.now(); },
		rateOrder() { uni.showToast({ title: '评价订单', icon: 'none' }); },
		buyAgain() { uni.showToast({ title: '再次租用', icon: 'none' }); }
	}
};
</script>

<style lang="scss" scoped>
.order-detail-page {
	background-color: #f7f8fa;
	min-height: 100vh;
	padding-bottom: 150rpx; // 为底部操作栏预留空间
}

.card-style {
	background-color: #fff;
	border-radius: 16rpx;
	margin: 20rpx 24rpx 0;
	padding: 24rpx 30rpx;
	box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.03);
}

.header-status {
	background-color: #fff;
	padding: 30rpx 30rpx 20rpx;
	.status-line {
		display: flex;
		align-items: center;
		justify-content: space-between; // 如果右侧有图标
		.status-text {
			font-size: 36rpx;
			font-weight: bold;
			color: #303133;
		}
	}
	.countdown-timer {
		font-size: 26rpx;
		color: #606266;
		margin-top: 15rpx;
		.time-segment {
			font-weight: bold;
			color: #fa3534; // 红色时间
			margin: 0 4rpx;
		}
	}
}

.address-section {
	display: flex;
	align-items: flex-start; // 地址可能多行
	.location-icon {
		margin-right: 15rpx;
		margin-top: 6rpx; // 微调对齐
		flex-shrink: 0;
	}
	.address-details {
		flex-grow: 1;
		.contact-info {
			margin-bottom: 8rpx;
			.name {
				font-size: 30rpx;
				font-weight: 500;
				color: #303133;
				margin-right: 20rpx;
			}
			.phone {
				font-size: 28rpx;
				color: #606266;
			}
		}
		.full-address {
			font-size: 26rpx;
			color: #606266;
			line-height: 1.5;
		}
	}
	.modify-address-btn {
		background-color: #f5f5f5;
		color: #333;
		border-radius: 30rpx;
		padding: 0 20rpx;
		font-size: 24rpx;
		height: 50rpx;
		line-height: 50rpx;
		margin-left: 20rpx;
		flex-shrink: 0;
		border: none;
		&::after { border: none; }
	}
}

.product-section {
	display: flex;
	align-items: center;
	.product-image {
		width: 120rpx;
		height: 120rpx;
		border-radius: 8rpx;
		margin-right: 20rpx;
		flex-shrink: 0;
		background-color: #f0f0f0;
	}
	.product-info {
		flex-grow: 1;
		margin-right: 20rpx;
		overflow: hidden;
		.product-name {
			font-size: 28rpx;
			color: #333;
			// 多行省略
			display: -webkit-box;
			-webkit-box-orient: vertical;
			-webkit-line-clamp: 2;
			overflow: hidden;
			text-overflow: ellipsis;
		}
	}
	.product-price {
		font-size: 28rpx;
		color: #333;
		font-weight: 500;
		flex-shrink: 0;
	}
}

.price-details-section {
	.price-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 15rpx 0;
		&:first-child { // 成交价的展开图标特殊处理
			uni-icons {
				margin-left: auto; // 推到价格左边
				margin-right: 10rpx;
			}
		}
		.label {
			font-size: 26rpx;
			color: #606266;
		}
		.value {
			font-size: 26rpx;
			color: #303133;
			&.actual-price {
				font-weight: bold;
				font-size: 30rpx;
				color: #fa3534;
			}
		}
	}
}

.order-info-section {
	.info-item {
		display: flex;
		// justify-content: space-between; // 不需要，让value自适应
		align-items: center;
		padding: 15rpx 0;
		font-size: 26rpx;
		.label {
			color: #606266;
			width: 180rpx; // 固定标签宽度，方便对齐
			flex-shrink: 0;
		}
		.value {
			color: #303133;
			flex-grow: 1;
			word-break: break-all; // 防止长编号不换行
			&.placeholder {
				color: #999;
				font-size: 24rpx;
			}
		}
		.copy-btn {
			background-color: #f5f5f5;
			color: #333;
			border-radius: 20rpx;
			padding: 0 15rpx;
			font-size: 22rpx;
			height: 40rpx;
			line-height: 40rpx;
			margin-left: 15rpx;
			border: none;
			&::after { border: none; }
		}
		uni-icons[type="right"] {
			margin-left: 10rpx;
		}
	}
	.toggle-more-info {
		display: flex;
		align-items: center;
		justify-content: center;
		color: #999;
		font-size: 24rpx;
		padding-top: 20rpx;
		text {
			margin-right: 6rpx;
		}
	}
}

.recommendation-section {
	margin-top: 30rpx;
	padding: 0 24rpx;
	.rec-title {
		display: flex;
		align-items: center;
		font-size: 30rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 20rpx;
	}
	.rec-placeholder {
		text-align: center;
		color: #ccc;
		padding: 50rpx 0;
		background-color: #fff;
		border-radius: 16rpx;
	}
}

.bottom-actions {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background-color: #fff;
	display: flex;
	justify-content: flex-end; // 按钮靠右
	align-items: center;
	padding: 15rpx 24rpx;
	box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.05);
	z-index: 100;
	.action-btn {
		height: 70rpx;
		line-height: 70rpx;
		border-radius: 35rpx;
		font-size: 26rpx;
		padding: 0 30rpx;
		margin-left: 20rpx;
		border: 1rpx solid #ccc;
		background-color: #fff;
		color: #333;
		display: flex;
		align-items: center;
		justify-content: center;

		&::after { border: none; }
		&.secondary-btn {
			// 联系卖家这种按钮可以更靠左
			margin-right: auto; 
			margin-left: 0;
		}
		&.primary-btn {
			background-color: #ff5000;
			color: #fff;
			border-color: #ff5000;
		}
	}
}

// 取消订单抽屉样式
.cancel-drawer-content {
	padding: 30rpx;
	padding-bottom: calc(30rpx + constant(safe-area-inset-bottom));
	padding-bottom: calc(30rpx + env(safe-area-inset-bottom));
	background-color: #fff;
	border-top-left-radius: 20rpx;
	border-top-right-radius: 20rpx;

	.drawer-title {
		font-size: 32rpx;
		font-weight: bold;
		text-align: center;
		margin-bottom: 40rpx;
		display: block;
	}
	.reason-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 25rpx 0;
		font-size: 28rpx;
		color: #333;
		&:not(:last-child) {
			border-bottom: 1rpx solid #f5f5f5;
		}
	}
	.drawer-actions {
		display: flex;
		margin-top: 40rpx;
		.drawer-btn {
			flex: 1;
			height: 80rpx;
			line-height: 80rpx;
			border-radius: 40rpx;
			font-size: 28rpx;
			text-align: center;
			&::after { border: none; }
			&.secondary {
				background-color: #f5f5f5;
				color: #333;
				margin-right: 20rpx;
			}
			&.primary {
				background-color: #FFC800; // 闲鱼黄
				color: #333;
				font-weight: bold;
				&:disabled {
					background-color: #f0f0f0;
					color: #aaa;
				}
			}
		}
	}
}
</style>